//
//  ZGLConfirmListController.m
//  ZeegingLottery
//
//  Created by Alfa Li on 2018/6/9.
//  Copyright © 2018年 蒂埃里. All rights reserved.
//

#import "ZGLConfirmListController.h"
#import "ZGLConfirmationView.h"
#import "ZGLBetConfirmCell.h"
#import "ZGLPopSerialPassView.h"
#import "ZGLMultiplesKeyboard.h"
#import "ZGLOrderPayController.h"
#import "ZGLLeftMenuController.h"


@interface ZGLConfirmListController ()<UITableViewDelegate,UITableViewDataSource>
{
    CGFloat keyboardHeight;
    CGFloat duration;
    NSInteger matchCount;     //已选场数
    NSInteger tagNum;
}

@property (nonatomic, strong)UITableView *confirmListView;
@property (nonatomic, strong)ZGLConfirmationView *confirmationView;   //调整方案
@property (nonatomic, strong)UILabel *headerTipLabel;       //截止提示
@property (strong, nonatomic)UILabel *footerTipLabel;       //玩法提示
@property (nonatomic, strong)UIButton *addMoreGameBtn;      //继续添加比赛
@property (strong, nonatomic)NSMutableArray *matchArray;
@property (strong, nonatomic)NSMutableArray *serialPassArray;   //串关列表
@property (strong, nonatomic)NSMutableArray *serialPassStateArray; //串关列表状态

@property (copy, nonatomic)NSString *ggType;  //
@property (copy, nonatomic)NSString *times;   //倍数
@property (copy, nonatomic)NSString *totalMoney; //应付金额
@property (nonatomic, copy) NSString *content; //赔率内容

@end

@implementation ZGLConfirmListController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = sRGBHexAlpha(0xF5F5F5, 1.0);
    self.title = @"已选投注列表";
    
    [self.view addSubview:self.headerTipLabel];
    [self.view addSubview:self.confirmListView];
    [self.view addSubview:self.confirmationView];
    [self.confirmListView.tableHeaderView addSubview:self.addMoreGameBtn];
    [self.confirmListView.tableFooterView addSubview:self.footerTipLabel];
    [self setupUI];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateBetContentJSON:) name:ZGLChangeBetContentJSON object:nil];
    
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    DLog(@"====释放");
}

- (void)setBetJSONDict:(NSDictionary *)betJSONDict
{
    if (betJSONDict) {
        _betJSONDict = betJSONDict;
        self.content = betJSONDict[@"content"];
        self.confirmationView.betJSONDict = betJSONDict;
    }
}

- (void)setConfirmMatchArr:(NSMutableArray *)confirmMatchArr
{
    if (confirmMatchArr) {
        
        _confirmMatchArr = confirmMatchArr;
        DLog(@"排序前--%@",confirmMatchArr);
        //按开赛时间先后顺序排序
        NSArray *Arr = [_confirmMatchArr sortedArrayUsingComparator:^NSComparisonResult(ZGLAgainstModel *obj1, ZGLAgainstModel *obj2) {
            
            NSString *obj1TimeStr = [PublicMethod timestampFromTimeString:obj1.matchtime];
            NSString *obj2TimeStr = [PublicMethod timestampFromTimeString:obj2.matchtime];
            NSComparisonResult result = [obj1TimeStr compare:obj2TimeStr];
            
            return result;
        }];
        DLog(@"排序后--%@",Arr);
        self.matchArray = Arr.mutableCopy;
        matchCount = self.matchArray.count;
        tagNum = matchCount;
        ZGLAgainstModel *model = self.matchArray[0];
        self.headerTipLabel.text = [NSString stringWithFormat:@"已选%ld场 投注截止：%@",matchCount,model.closetime];
        self.confirmationView.passwayButton.viewTitle = [NSString stringWithFormat:@"%ld串1",matchCount];
        
    }
}

#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return matchCount;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
//    ZGLBetConfirmCell *cell = [ZGLBetConfirmCell betConfirmCellWithTableView:tableView];
    ZGLBetConfirmCell *cell = [ZGLBetConfirmCell betConfirmCellWithTableView:tableView IndexPath:indexPath];
    WS(weakself)
    
    //反选
    cell.countBlock = ^(NSInteger num) {

        if (weakSelf.selectedCountBlock) {
            weakSelf.selectedCountBlock(num);
        }
        
        matchCount = num;
        if (num<=1) {
            weakSelf.confirmationView.passwayButton.viewTitle = [NSString stringWithFormat:@"过关方式"];
        }else{
            
            weakSelf.confirmationView.passwayButton.viewTitle = [NSString stringWithFormat:@"%ld串1",num];
            
        }
        
        if (num<tagNum) {
            
            tagNum = num;
            DLog(@"减少一场");
            
            DLog(@"self.serialPassArray.count--%@，self.serialPassStateArray.count--%@",self.serialPassArray,self.serialPassStateArray);
            if (num >= 1 ) {
                
                if (self.serialPassStateArray.count>0) {
                    
                    DLog(@"前self.serialPassStateArray--%@,self.serialPassArray--%@",self.serialPassStateArray,self.serialPassArray);
                    
                    [self.serialPassStateArray replaceObjectAtIndex:num-1 withObject:@"0"];
                    [self.serialPassArray removeObject:[NSString stringWithFormat:@"%ld001",num+1]];
                    
                    DLog(@"后self.serialPassStateArray--%@,self.serialPassArray--%@",self.serialPassStateArray,self.serialPassArray);
                    
                    [self setButtonTitle];//串关按钮
                    
                }
                else{
                    
                    self.ggType = [NSString stringWithFormat:@"%ld001",num];
                }

            }

        }else{
            
            tagNum = num;
            self.ggType = [NSString stringWithFormat:@"%ld001",num];
            DLog(@"没减少场次");
            [self setButtonTitle];

        }
        
        [[NSNotificationCenter defaultCenter]postNotificationName:ZGLChangeBetContentJSON object:self.serialPassArray];
        
    };

    ZGLAgainstModel *model = self.matchArray[indexPath.row];
    cell.model = model;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 150;

}

#pragma mark - Method

- (void)updateBetContentJSON:(NSNotification *)notifi
{
    DLog(@"有更新--%@",notifi);
    
    //串关方式
    __block NSString *ggType;
    if ([notifi.object isKindOfClass:[NSArray class]]) {
        
        NSArray *ggTypeArr = notifi.object;
        if (ggTypeArr.count>0) {
            ggType = [ggTypeArr componentsJoinedByString:@";"];
            self.ggType = ggType;
            
        }else{
            ggType = [NSString stringWithFormat:@"%ld001",matchCount];
        }
        
    }
    else{
        if (self.ggType) {
            ggType = self.ggType;
        }else{
            
            ggType = [NSString stringWithFormat:@"%ld001",matchCount];
        }
    }
    
    //倍数
    int num = 0;
    if ([notifi.object isKindOfClass:[NSNumber class]]) {
        
        NSNumber *numBer = notifi.object;
        if (numBer.integerValue>0) {
            num = numBer.intValue;
            self.times = [NSString stringWithFormat:@"%d",num];
        }else{
            
            if (self.times) {
                num = [self.times intValue];
            }else{
                num = 10;
            }
        }
    }else{
        
        if (self.times) {
            num = [self.times intValue];
        }else{
            
            num = 10;
        }
    }
    
    //计算注数和奖金
    NSString *json = [Calculator betContentJSONWith:ApplicationDelegate.jsonContentArr];
    NSDictionary *jsonDict = [Calculator calculator:json ggType:ggType times:num lotteryId:46];
    NSMutableDictionary *mtJsonDict = jsonDict.mutableCopy;
    int betNum = [jsonDict[@"bet_num"] intValue];
    int numStr = betNum*num*2; //总注数×2×倍数
    self.totalMoney = [NSString stringWithFormat:@"%d",numStr]; //应付金额
    [mtJsonDict setObject:@(numStr) forKey:@"amount"];
    [mtJsonDict setObject:json forKey:@"content"]; //投注内容
    self.betJSONDict = mtJsonDict.copy;
    _confirmationView.betJSONDict = mtJsonDict.copy;
    DLog(@"%@",mtJsonDict);
    
}

//继续选择比赛
- (void)continueToSelect:(UIButton *)sender
{
    
    [self.navigationController popViewControllerAnimated:YES];
}

//串关弹窗
- (void)showsSelection
{
    //弹出串关列表
    ZGLPopSerialPassView *SerialPassView = [[ZGLPopSerialPassView alloc]init];
    SerialPassView.count = ApplicationDelegate.jsonContentArr.count;
    if (_serialPassArray.count>0 && _serialPassStateArray.count>0) {
        //传入选中
        SerialPassView.InComeSelectedBtnStateArray = self.serialPassStateArray.mutableCopy;
        SerialPassView.InComeSelectedBtnArray = self.serialPassArray.mutableCopy;

        
    }
    
    //回调
    WS(weakself)
    SerialPassView.SerialPassArrayBlock = ^(NSArray *btnArray, NSArray *stateArray) {
        
        weakSelf.serialPassStateArray = stateArray.mutableCopy;
        weakSelf.serialPassArray = btnArray.mutableCopy;
        [weakSelf setButtonTitle];

        dispatch_async(dispatch_get_main_queue(), ^{
            
            [[NSNotificationCenter defaultCenter] postNotificationName:ZGLChangeBetContentJSON object:btnArray];
            
        });
        
    };
    [SerialPassView showView];
    
}

//加倍键盘
- (void)popKeyboard
{
    ZGLMultiplesKeyboard *multiKeyboard = [[ZGLMultiplesKeyboard alloc]init];
    multiKeyboard.beiShuNumStr = self.times;
    multiKeyboard.numBlock = ^(NSInteger num) {
        
        //倍数回调
        self.confirmationView.changeBeishu.beiShuNum = num;
        DLog(@"倍数回调--%ld",num);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [[NSNotificationCenter defaultCenter]postNotificationName:ZGLChangeBetContentJSON object:@(num)];
        });
        
    };
    
    [multiKeyboard showView];
    
    
}

//提交订单
- (void)submitScenariosBtnClick:(UIButton *)sender
{
    sender.enabled = NO;//防止连续点击
    NSMutableDictionary *mtDictionary = self.betJSONDict.mutableCopy;
    if (!self.times) {
        self.times = @"10";
    }
    if (!self.ggType) {
        self.ggType = [NSString stringWithFormat:@"%ld001",tagNum];
    }
    NSString *multiple = self.times;
    NSString *group_type = self.ggType;
    [mtDictionary setValue:@"46" forKey:@"lottery_id"];
    [mtDictionary setValue:multiple forKey:@"multiple"];
    [mtDictionary setValue:group_type forKey:@"group_type"];
    __block NSString *drawStr = @"";
    [ApplicationDelegate.jsonContentArr enumerateObjectsUsingBlock:^(ZGLAgainstModel *model, NSUInteger idx, BOOL * _Nonnull stop) {
        
        drawStr = [drawStr stringByAppendingString:[NSString stringWithFormat:@"%@;",model.draw]];
//        drawStr = [drawStr stringByAppendingPathComponent:@";"];
        
    }];
    drawStr = [PublicMethod removeLastOneChar:drawStr];
    [mtDictionary setValue:drawStr forKey:@"darw"];
    DLog(@"drawStr--%@",drawStr);
    
    DLog(@"mtDictionary--%@",mtDictionary);
    if (sZGLUserInfoModel.usercheck == YES) {
        
        DLog(@"提交订单去支付");
        
        /*
         NSDictionary *param = @{
         @"token" : token,
         @"lottery_id" : lotteryId,
         @"content" : content,
         @"darw" : darw,
         @"group_type" : groupType,
         @"multiple" : multiple,
         @"amount" : amount,
         @"bet_num" : betNum,
         @"max_prize" : maxPrize,
         @"min_prize" : minPrize
         
         };
         */
        NSString *token = sZGLUserInfoModel.token;
        [mtDictionary setValue:token forKey:@"token"];

//        ZGLOrderPayController *orderPayVC = [[ZGLOrderPayController alloc]init];
//        NSString *totalStr = [NSString stringWithFormat:@"%@",self.betJSONDict[@"amount"]];
//        orderPayVC.totalMoney = @"10000.00";
//        orderPayVC.jsonBet = mtDictionary.copy;
//        [self.navigationController pushViewController:orderPayVC animated:YES];
        
        [self creatOrderWithBetContent:mtDictionary.copy];
        
        
    }else{
        
        DLog(@"未登录");
        sender.enabled = YES;
        ZGLLeftMenuController *leftMenuVc = [[ZGLLeftMenuController alloc]init];
        [self cw_showDrawerViewController:leftMenuVc animationType:CWDrawerAnimationTypeMask configuration:nil];
        
        [EasyTextView showText:@"请先登录"];
        
    }
    
    
}

//下单
- (void)creatOrderWithBetContent:(NSDictionary *)betContent
{
    //菊花
    [EasyLoadingView showLoadingText:@"" config:^EasyLoadingConfig *{
        
        return [EasyLoadingConfig shared].setLoadingType(LoadingShowTypeIndicator);
    }];
    
    
    NSDictionary *paramer = betContent;
    NSString *token = paramer[@"token"];
    NSString *lottery_id = paramer[@"lottery_id"];
    NSString *content = paramer[@"content"];
    NSString *darw = paramer[@"darw"];
    NSString *groupType = paramer[@"group_type"];
    NSString *multiple = paramer[@"multiple"];
    NSString *amount = paramer[@"amount"];
    NSString *betNum = paramer[@"bet_num"];
    NSString *max = [PublicMethod keepTwoDecimalPoint:paramer[@"max_prize"]];
    NSString *min = [PublicMethod keepTwoDecimalPoint:paramer[@"min_prize"]];
    
    //    NSArray *contentArr = [PublicMethod stringToJSON:content];
    //    DLog(@"orderParame--%@,\n contentArr--%@",paramer,contentArr);
    
    [sZGLHTTPRequestManager creatOrderWithToken:token LotteryId:lottery_id Content:content Darw:darw GroupType:groupType Multiple:multiple Amount:amount BetNum:betNum MaxPrize:max MinPrize:min Success:^(id responseData) {

        NSString *code = responseData[@"code"];
        NSDictionary *dataDict = responseData[@"data"];
        if ([code integerValue] == 1) {
            DLog(@"下单成功");

            _confirmationView.submitScenariosBtn.enabled = YES;
            [EasyLoadingView hidenLoading];
            ZGLOrderPayController *orderPayVC = [[ZGLOrderPayController alloc]init];
            orderPayVC.orderInfoDict = dataDict;
            [self.navigationController pushViewController:orderPayVC animated:YES];

        }else{
            DLog(@"下单失败");
            [EasyLoadingView hidenLoading];
            [EasyTextView showErrorText:@"下单失败"];
            _confirmationView.submitScenariosBtn.enabled = YES;

        }

    } Fail:^(ZGLRespondStatusCode bef_status, NSString *bef_message, NSError *error) {

        DLog(@"下单失败");
        [EasyLoadingView hidenLoading];
        [EasyTextView showErrorText:@"下单失败"];
        _confirmationView.submitScenariosBtn.enabled = YES;
    }];
    
    
}



- (void)setButtonTitle
{
    DLog(@"self.serialPassArray-=%@",self.serialPassArray);
    if (self.serialPassArray.count>0) {
        
        //排序
        NSArray *SortArr = [self.serialPassArray sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
            
            NSComparisonResult result = [obj1 compare:obj2];
            
            return result;
        }];
        
        NSString *str = [[NSString alloc]init];
        for (NSString *string in SortArr) {
            DLog(@"%@",string);
            NSString *cutStr = [string substringWithRange:NSMakeRange(0, 1)];
            
            str = [str stringByAppendingString:[NSString stringWithFormat:@"%@串1,",cutStr]];
        }
        str = [str substringToIndex:([str length]-1)];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            self.confirmationView.passwayButton.viewTitle = str;
            
        });
    }
    
}



#pragma mark - lazy


- (NSMutableArray *)serialPassStateArray
{
    if (!_serialPassStateArray) {
        _serialPassStateArray = [NSMutableArray array];
    }
    return _serialPassStateArray;
}

- (NSMutableArray *)serialPassArray
{
    if (!_serialPassArray) {
        _serialPassArray = [NSMutableArray array];
    }
    return _serialPassArray;
}

- (NSMutableArray *)matchArray
{
    if (!_matchArray) {
        _matchArray = [NSMutableArray array];
    }
    return _matchArray;
}

//投注提示
- (UILabel *)headerTipLabel
{
    if (!_headerTipLabel) {
        _headerTipLabel = [[UILabel alloc]init];
        _headerTipLabel.font = [UIFont systemFontOfSize:13];
        _headerTipLabel.textColor = detailTextColor;
        _headerTipLabel.textAlignment = 1;
        _headerTipLabel.text = @"已选10场 投注截止：2018-06-09 17:50:00";
    }
    
    return _headerTipLabel;
}

- (UILabel *)footerTipLabel
{
    if (!_footerTipLabel) {
        _footerTipLabel = [[UILabel alloc]init];
        _footerTipLabel.text = @"注：全场90分钟(含伤停补时,不含加时赛及点球大战),页面奖金进攻参考,实际奖金以投注成功时为准";
        _footerTipLabel.textAlignment = 1;
        _footerTipLabel.numberOfLines = 0;
        _footerTipLabel.textColor = [UIColor grayColor];
        _footerTipLabel.font = [UIFont systemFontOfSize:labelFontSize];
    }
    return _footerTipLabel;
}


//
- (UITableView *)confirmListView
{
    if (!_confirmListView) {
        _confirmListView = [[UITableView alloc]init];
        _confirmListView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _confirmListView.backgroundColor = ViewBackgroundColor;
        _confirmListView.delegate = self;
        _confirmListView.dataSource = self;
        UIView *headerView =[[UIView alloc]init];
        headerView.frame = CGRectMake(0, 0, UI_SCREEN_WIDTH, 50);
        _confirmListView.tableHeaderView = headerView;
    }
    
    return _confirmListView;
}

- (ZGLConfirmationView *)confirmationView
{
    if (!_confirmationView) {
        _confirmationView = [[ZGLConfirmationView alloc]init];
//        [_confirmationView.passwayButton addTarget:self action:@selector(showsSelection) forControlEvents:UIControlEventTouchUpInside];
        [_confirmationView.changeBeishu.beiShuBtn addTarget:self action:@selector(popKeyboard) forControlEvents:UIControlEventTouchUpInside];
        [_confirmationView.submitScenariosBtn addTarget:self action:@selector(submitScenariosBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [_confirmationView.passwayButton selectButton:^(LYDCustomButton *btu) {
            
            [self showsSelection];
        }];
    }
    
    return _confirmationView;
}

- (UIButton *)addMoreGameBtn
{
    if (!_addMoreGameBtn) {
        _addMoreGameBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_addMoreGameBtn setTitle:@"+ 继续选择比赛" forState:UIControlStateNormal];
        [_addMoreGameBtn setBackgroundColor:[UIColor whiteColor]];
        [_addMoreGameBtn setTitleColor:mainTextColor forState:UIControlStateNormal];
        [_addMoreGameBtn addTarget:self action:@selector(continueToSelect:) forControlEvents:UIControlEventTouchUpInside];
        _addMoreGameBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        _addMoreGameBtn.layer.borderColor = BorderColor.CGColor;
        _addMoreGameBtn.layer.borderWidth = kBorderWidth;
        _addMoreGameBtn.layer.cornerRadius = 3;
        _addMoreGameBtn.layer.masksToBounds = YES;
    }
    
    return _addMoreGameBtn;
}

- (void)setupUI
{
    CGFloat sConfirmationH = IS_IPHONE_X ? 180 : 156;
    
    [_headerTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.view).offset(10);
        make.centerX.equalTo(self.view);

    }];
    
    [_addMoreGameBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(_confirmListView.tableHeaderView).offset(5);
        make.centerX.equalTo(_confirmListView.tableHeaderView);
        make.width.equalTo(@(UI_SCREEN_WIDTH-40));
        make.height.equalTo(@(40));
        
    }];
    
//    []
    
    [_confirmationView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.equalTo(self.view);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.equalTo(@(sConfirmationH));
        
    }];
    
    [_confirmListView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(_headerTipLabel.mas_bottom).offset(10);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(_confirmationView.mas_top);
        
    }];
    
}

@end
